#pragma once

#include <iostream>
#include <string>
#include <sys/select.h>
#include <cerrno>
#include "Sock.hpp"
#include "Err.hpp"
#include "log.hpp"

const static int gport = 8080;
typedef int type_t;

class SelectServer
{
public:
    static const int N = sizeof(fd_set) * 8;

    SelectServer(uint16_t port = gport) : _port(port)
    {
    }
    ~SelectServer()
    {
        _listensock.Close();
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listhen();

        for (int i = 0; i < N; i++)
        {
            _fdarray[i] = defaultfd;
        }
    }

    void Accepter()
    {
        std::cout << "新连接到来" << std::endl;
        // 开始accept
        std::string clientip;
        uint16_t clientport;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;

        logmessage(DEBUG, "[%s:%d] sock: %d", clientip.c_str(), clientport, sock);

        // 把获得的fd添加进数组
        int i = 0;
        for (i = 1; i < N; i++)
        {
            if (_fdarray[i] == defaultfd)
                break;
        }
        if (i >= N)
        {
            close(sock);
            logmessage(WARNING, "sockfd array is full");
        }
        else
        {
            _fdarray[i] = sock;
        }
    }

    void Handerevent(fd_set &rfds)
    {
        for (int i = 0; i < N; i++)
        {
            if (_fdarray[i] == defaultfd)
                continue;

            if (_fdarray[i] == _listensock.Fd() &&
                FD_ISSET(_listensock.Fd(), &rfds)) // 处理新连接事件
            {
                Accepter();
            }
            else if (FD_ISSET(_fdarray[i], &rfds)) // 处理读事件就绪
            {
                char buffer[1024];
                ssize_t s = recv(_fdarray[i], buffer, sizeof(buffer), 0);
                if (s > 0)
                {
                    buffer[s - 1] = '\0';
                    std::cout << "client# " << buffer << std::endl;

                    // 将数据发送回去
                    std::string echo = buffer;
                    echo += " [select server echo]";
                    send(_fdarray[i], echo.c_str(), echo.size(), 0);
                }
                else
                {
                    if (s == 0)
                    {
                        logmessage(INFO, "client quit...");
                    }
                    else
                    {
                        logmessage(WARNING, "recv error,client quit...");
                    }
                    close(_fdarray[i]);
                    _fdarray[i] = defaultfd;
                }
            }
        }
    }

    void start()
    {
        // struct timeval timeout = {2, 0};
        _fdarray[0] = _listensock.Fd();
        while (true)
        {
            // 每次同步需要关心的fd
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = _fdarray[0];
            for (int i = 0; i < N; i++)
            {
                if (_fdarray[i] == defaultfd)
                    continue;

                FD_SET(_fdarray[i], &rfds);
                if (maxfd < _fdarray[i])
                    maxfd = _fdarray[i];
            }
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);

            switch (n)
            {
            case 0:
                logmessage(DEBUG, "time out...");
                break;
            case -1:
                logmessage(WARNING, "select error, %s", strerror(errno));
                break;
            default:
                logmessage(DEBUG, "有文件已就绪: %d", n);
                Handerevent(rfds);
                break;
            }
        }
    }

private:
    uint16_t _port;
    Sock _listensock;
    type_t _fdarray[N];
};